package com.lenovo.agent.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.lenovo.agent.config.GitLabConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class DifyAIReviewService implements AIReviewService {
    
    @Autowired
    private GitLabConfig gitLabConfig;
    
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public String performCodeReview(String changes) {
        try {
            // 准备请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + gitLabConfig.getDifyApiKey());
            
            // 准备请求体
            ObjectNode requestBody = objectMapper.createObjectNode();
            ObjectNode inputs = objectMapper.createObjectNode();
            inputs.put("query", "请作为专业的代码审查员，审查以下代码变更，并提供具体的改进建议。" +
                    "关注以下方面：代码质量、性能优化、安全性、可维护性、最佳实践。\n\n" + changes);
            inputs.put("tag", 0);
            
            requestBody.set("inputs", inputs);
            requestBody.put("response_mode", "blocking");
            requestBody.put("user", "gitlab-review");
            
            // 发送请求
            HttpEntity<String> requestEntity = new HttpEntity<>(
                objectMapper.writeValueAsString(requestBody), 
                headers
            );
            
            ResponseEntity<JsonNode> response = restTemplate.exchange(
                gitLabConfig.getDifyUrl(),
                HttpMethod.POST,
                requestEntity,
                JsonNode.class
            );
            
            // 解析响应
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                String review = response.getBody()
                    .path("answer")
                    .asText();
                
                return "## AI 代码审查意见\n\n" + review;
            } else {
                throw new RuntimeException("调用 Dify API 失败: " + response.getStatusCode());
            }
            
        } catch (Exception e) {
            log.error("AI 代码审查失败", e);
            return "AI 代码审查过程中发生错误: " + e.getMessage();
        }
    }
} 